package com.da.javatest.thread.juc.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author chenlida
 * @date 2020/7/11 22:53
 * 代码中许可数量为1， semaphore.tryAcquire(1,TimeUnit.SECONDS);：表示尝试在1秒内获取许可，获取成功立即返回true，
 * 超过1秒还是获取不到，返回false。线程t1获取许可成功，之后休眠了5秒，从输出中可以看出t2和t3都尝试了1秒，获取失败。
 */
public class Semaphore4 {
    private static Semaphore semaphore = new Semaphore(1);

    public static class MyThread extends Thread {
        public MyThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            Thread thread = Thread.currentThread();
            //获取许可是否成功
            boolean acquireSuccess = false;
            try {
                System.out.println(thread.getName() + "尝试获得许可,当前可用许可为:" + semaphore.availablePermits());
                acquireSuccess = semaphore.tryAcquire(1, TimeUnit.SECONDS);
                if (acquireSuccess) {
                    System.out.println(thread.getName() + "尝试获得许可成功,当前可用许可为:" + semaphore.availablePermits());
                    TimeUnit.SECONDS.sleep(5);
                } else {
                    System.out.println(thread.getName() + "尝试获得许可失败,当前可用许可为:" + semaphore.availablePermits());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (acquireSuccess) {
                    semaphore.release();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Semaphore4.MyThread t1 = new Semaphore4.MyThread("t1");
        t1.start();
        TimeUnit.SECONDS.sleep(1);
        Semaphore4.MyThread t2 = new Semaphore4.MyThread("t2");
        t2.start();
        TimeUnit.SECONDS.sleep(1);
        Semaphore4.MyThread t3 = new Semaphore4.MyThread("t3");
        t3.start();
    }
}
